package com.tangyee.home_blood_center.activities;

import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.tangyee.home_blood_center.utils.DialogUtils;
import com.tangyee.home_blood_center.utils.HandleBackUtil;
import com.tangyee.R;
import com.tangyee.home_blood_center.utils.DialogUtils;
import com.tangyee.home_blood_center.utils.HandleBackUtil;

/**
 * 自定义的基础Activity，抽取了Activity托管Fragment时的重复代码
 */
public abstract class SingleFragmentActivity extends FragmentActivity {
    protected abstract Fragment createFragment();

    private Dialog mDialog;

    Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);

        //禁止横屏，不禁止太多坑了
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // 启动加载弹窗
        mDialog = DialogUtils.createLoadingDialog(SingleFragmentActivity.this, "加载中...");

    }

    @Override
    protected void onStart() {
        super.onStart();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // 耗时操作都在这里
                FragmentManager fm = getSupportFragmentManager();
                Fragment fragment = fm.findFragmentById(R.id.fragment_container);
                if (fragment == null) {
                    fragment = createFragment();
                    fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
                }
            }
        }, 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // onResume执行后延迟300毫秒后停止加载动画
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                mProgressBar.setVisibility(View.GONE);
                DialogUtils.closeDialog(mDialog);
            }
        }, 200);
    }

    /**
     * 重写返回键点击方法，让其执行自定义的方法（将返回事件分发给所有继承了BaseFragment的fragment）
     */
    @Override
    public void onBackPressed() {
        if (!HandleBackUtil.handleBackPress(this)) {
            super.onBackPressed();
        }
    }

}
